﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ControlAccessUser.DataAccess
{
    public static class DataAccessLogin
    {
        public static void InsertNewLogin(Model.Login Login)
        {
            ControlAccessUserEntities.Instance.Logins.Add(Login);
            ControlAccessUserEntities.Instance.SaveChanges();
        }

        public static void RegisterLogout(Model.User user)
        {
            try
            {
                var Query = (from Login in ControlAccessUserEntities.Instance.Logins
                             where Login.UserId == user.UserId && Login.DataTimeLogoutUser == null
                             select Login).ToList().Last();
                Query.DataTimeLogoutUser = DateTime.Now;
                ControlAccessUserEntities.Instance.SaveChanges();
            }
            catch (Exception)
            {

                throw new Exception(Model.Message.ErrorLogout);
            }                
                    
        }

        public static ICollection<Model.Login> SearchLastRegisterLogin(Model.User User)
        {
            return (from Login in ControlAccessUserEntities.Instance.Logins
                    where Login.UserId == User.UserId && Login.LoginId == (from Log in ControlAccessUserEntities.Instance.Logins
                                                                           select Log.LoginId).Max()
                    select Login).ToList();
        }

        public static ICollection<Model.Login> SearchLoginsByUserAndSession(Model.User User, DateTime DateTimeInit, DateTime DateTimeEnd)
        {
            return (from Login in ControlAccessUserEntities.Instance.Logins
                    where Login.UserId == User.UserId 
                            && DateTimeInit.CompareTo(Login.DataTimeLoginUser)<=0 && DateTimeEnd.CompareTo(Login.DataTimeLogoutUser.Value)>=0
                    select Login).ToList();
        }
    }
}
